﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using ButsaScraperLib;
using HtmlAgilityPack;

namespace ButsaScraperConsoleTest
{
	class Program
	{
		static void Main(string[] args)
		{
			//LoadCountryTeams();
			string homeTeamId = ButsaManager.Instance.GetTeamIdByName("Фрибур");
			string guestTeamId = ButsaManager.Instance.GetTeamIdByName("Цольбрюк");

			Team homeTeam = ButsaManager.Instance.GetTeamById(homeTeamId);
			Team guestTeam = ButsaManager.Instance.GetTeamById(guestTeamId);

			Console.ReadKey();
		}

		private static void ReadLastResult()
		{
			Score score = ButsaManager.Instance.GetMatchResultForTeams("5954", "5976");
			Console.WriteLine(score.ToString());
		}

		private static void LoadDivisions()
		{
			var divisions = ButsaManager.Instance.GetAllDivisionsNames();
			foreach (var division in divisions)
			{
				Console.WriteLine(String.Format("{0} - {1}", division.Id, division.Name));
			}
		}

		private static void LoadPlayer()
		{
			var player = ButsaManager.Instance.GetPlayerById("271777");
			if (player != null)
			{
				Console.WriteLine(player.Name);
				Console.WriteLine(player.TakingSkill);
				Console.WriteLine(player.MarkingSkill);
				Console.WriteLine(player.DribblingSkill);
				Console.WriteLine(player.ReceptionSkill);
				Console.WriteLine(player.StaminaSkill);
				Console.WriteLine(player.PassSkill);
				Console.WriteLine(player.StrikeValueSkill);
				Console.WriteLine(player.StrikeAccuracySkill);

				Console.WriteLine(player.TotalSkill);
				Console.WriteLine(player.Age);
				//позиции

				Console.WriteLine(player.PhysicalFitness);
				Console.WriteLine(player.Morality);
				Console.WriteLine(player.Tiredness);
				Console.WriteLine(player.CalculatedTotalSkill);

			}
		}

		private static void LoadTeam()
		{
			ButsaManager.Instance.GetTeamById("5976");
		}

		private static void LoadCountryTeams()
		{
			string[] urls = new string[] {"http://butsa.ru/xml/ratings/ratings.php?class=1&id=28&Country=150&Division=",
				"http://butsa.ru/xml/ratings/ratings.php?page=2&type=ratings/teams&act=select&id=28&class=1&Country=150"};

			const string commandsXPath = "/body[1]/div[1]/table[1]/tr[2]/td[1]/table[1]/tr[1]/td[2]/table[1]/tr[1]/td[2]/table[1]/tr[7]/td[1]/table[1]/tr[1]/td[2]/table[1]/tr[2]/td[1]/table[1]/tr[1]/td[1]/table[2]";

			for(int p = 0; p< urls.Length;p++)
			{
				string loadedPage1 = LoadPage(urls[p]);
				TextReader loadedPage1Reader = new StringReader(loadedPage1);
				HtmlDocument page1Doc = new HtmlDocument();
				page1Doc.Load(loadedPage1Reader);

				var table = page1Doc.DocumentNode.SelectSingleNode(commandsXPath);

				var rowsCount = table.ChildNodes.Where(item => String.Compare(item.Name, "tr", true) == 0).Count();
				for (int i = 2; i < rowsCount; i++)
				{
					var teamName = table.SelectSingleNode(String.Format("tr[{0}]/td[2]/a[1]", i)).InnerText;
					var teamIdRef = table.SelectSingleNode(String.Format("tr[{0}]/td[2]/a[1]", i)).Attributes["href"].Value;
					Regex extractIdRegex = new Regex("/roster/(?<id>[^/]+)");
					Match match = extractIdRegex.Match(teamIdRef);
					if (match.Success)
					{
						var teamId = match.Groups["id"].Captures[0].Value;
						TeamIdByNameCache.Instance.AddToCache(teamName, teamId);
					}
				}
			}
			TeamIdByNameCache.Instance.Dispose();
		}

		private static string LoadPage(string url)
		{
			HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
			httpWebRequest.Proxy = WebRequest.DefaultWebProxy;
			httpWebRequest.ServicePoint.Expect100Continue = false;
			httpWebRequest.Method = "POST";
			httpWebRequest.ContentType = "application/x-www-form-urlencoded";
			Stream requestStream = httpWebRequest.GetRequestStream();
			byte[] bytes = Encoding.GetEncoding(1251).GetBytes("auth_name=RollingStone&auth_pass=,jncdfyf");
			requestStream.Write(bytes, 0, bytes.Length);
			requestStream.Close();
			WebResponse webResponse = httpWebRequest.GetResponse();
			string loadedPage = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("UTF-8")).ReadToEnd();
			return loadedPage;
		}
	}
}
